package com.xy.controller

import java.io._
import javax.servlet.http.HttpServletResponse

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestMapping, RequestParam}

/**
  * Created by xiaoyuan on 2017/11/16.
  */
@Controller
class FileDownController {
  @RequestMapping(Array("/down"))
  def down(@RequestParam(value="fileName", defaultValue="") fileName:String,res:HttpServletResponse): Unit ={
    val buff = new Array[Byte](1024)
    var bis : InputStream = null;
    var os : OutputStream =null;
    try {
      os = res.getOutputStream
      val file = new File("D:/"+fileName)
      if (!file.exists) return
      res.setHeader("content-type", "application/octet-stream")
      res.setContentType("application/octet-stream")
      res.setHeader("Content-Disposition", "attachment;filename=" + fileName)
      bis = new BufferedInputStream(new FileInputStream(file))
      var i = bis.read(buff)
      while ( {
        i != -1
      }) {
        os.write(buff, 0, buff.length)
        i = bis.read(buff)
      }
      os.flush()
    } catch {
      case e: IOException =>
        e.printStackTrace()
    } finally if (bis != null) try
      bis.close()
    catch {
      case e: IOException =>
        e.printStackTrace()
    }
  }
}
